<?php

namespace App\Services\ApplyGoldProductReselling;

use Closure;
use App\Models\User;
use Illuminate\Support\Facades\Redis;
use App\Http\Controllers\Api\V1\Requests\FormRequest;

class ApplyGoldProductBatchResellingRequest extends FormRequest
{
	protected array $pendingCacheIds = [];

	public function rules(): array
	{
		return [
			'records' => ['array', $this->records()]
		];
	}

	public function records(): Closure
	{
		return function ($key, $value, $fail) {

			/**
			 * @var User $user
			 */
			$user = $this->user();

			$cachedIds = collect($value)->unique();

			if ($cachedIds->count() <= 0) {
				return $fail('请提供正确的抢购记录');
			}

			$totalBeans = big_decimal(0);

			foreach ($cachedIds as $cid) {
				if (! Redis::exists($cid)) {
					return $fail("目标记录不存在");
				} elseif (! Redis::hGet($cid, 'is_paid')) {
					return $fail("目标记录未支付");
				} elseif (Redis::hGet($cid, 'is_resell_applying')) {
					return $fail("不可重复申请寄售");
				} elseif (Redis::hGet($cid, 'has_applied_to_resell')) {
					return $fail("不可重复申请寄售");
				} elseif (Redis::hGet($cid, 'is_split_applying')) {
					return $fail("目标记录正在申请超额返");
				} elseif (Redis::hGet($cid, 'has_applied_to_split')) {
					return $fail("目标记录已申请超额返");
				} elseif (Redis::hGet($cid, 'is_take_applying')) {
					return $fail("目标记录正在申请发货");
				} elseif (Redis::hGet($cid, 'has_applied_to_take')) {
					return $fail("目标记录已申请发货");
				}
				$totalBeans = $totalBeans->plus(Redis::hGet($cid, 'pay_gold_beans'));
			}

			if ($totalBeans->isGreaterThan($user->gold_beans)) {
				return $fail('可用金豆不足');
			}

			$this->pendingCacheIds = $cachedIds->toArray();

			return true;
		};
	}

	public function getPendingCacheIds(): array
	{
		return $this->pendingCacheIds;
	}
}
